package com.tyl.single单例模式;

import java.lang.reflect.Constructor;

/**
 * @author 懒汉式单例模式
 */
public class LazyMan {
    private LazyMan(){
        synchronized (LazyMan.class){
            if (lazyMan!=null){
                throw new RuntimeException("不要试图使用反射破坏");
            }
        }
        System.out.println(Thread.currentThread().getName());
    }
    /**volatile避免指令重排**/
    private volatile static LazyMan lazyMan;
    /**上锁，双重检测懒汉模式DCL模式**/
    public static LazyMan getInstance(){
        if(lazyMan==null){
            synchronized (LazyMan.class)
            {
                if(lazyMan==null){
                    lazyMan=new LazyMan();
                }
            }
        }
        return  lazyMan;
    }
    //反射
    public static void main(String[] args) throws Exception {
        //LazyMan instance = LazyMan.getInstance();
        Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
        /**无视私有构造器**/
        constructor.setAccessible(true);
        LazyMan instance = constructor.newInstance ();
        LazyMan instance2 = constructor.newInstance ();
        System.out.println(instance);
        System.out.println(instance2);
    }

    ////执行线程
    //public static void main(String[] args) {
    //    for (int i = 0; i <10 ; i++) {
    //        new Thread(()->{
    //            LazyMan.getInstance();
    //        }).start();
    //    }
    //}
}